package com.ibm.cloud.banking.account.route;

import com.ibm.cloud.banking.account.constant.RouteInfo;
import com.ibm.cloud.banking.account.convert.AccountInfoMapper;
import com.ibm.cloud.banking.account.service.IAccountInfoService;
import com.ibm.cloud.banking.media.service.IMediaCardService;
import com.ibm.cloud.banking.prod.facade.IProdSaleFacade;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.SagaPropagation;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import javax.annotation.Resource;

import static com.ibm.cloud.banking.account.constant.AccountDomainConstant.OPEN_ACCOUNT_REVERSE_KEY;

/**
 * replace desc in here
 *
 * @author HanDong
 * @date 2022/7/17
 */
@Configuration
public class OpenAccountRoute extends RouteBuilder {


    @Resource
    private IMediaCardService mediaCardService;

    @Resource
    private IProdSaleFacade prodSaleFacade;

    @Resource
    private IAccountInfoService accountInfoService;



    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Override
    public void configure(){
        from(RouteInfo.OPEN_ACCOUNT.servNo)
                .routeDescription(RouteInfo.OPEN_ACCOUNT.desc)
                .routeId(RouteInfo.OPEN_ACCOUNT.id)
                .saga()
                .propagation(SagaPropagation.REQUIRES_NEW)
                .log("开立结算账户")
                .to(RouteInfo.CHECK_PROD_INFO.servNo)
                .process(exchange ->
                {
                    exchange.getIn().setBody(accountInfoMapper.mapToDto((Map)exchange.getIn().getBody()));
                })
                .to("direct:openAccount")
                .to("direct:finalize").log("Done!");

        from("direct:openAccount").saga()
                .propagation(SagaPropagation.MANDATORY)
                .compensation("direct:reverseAccount")
                .bean(accountInfoService,"createAccount")
                .option(OPEN_ACCOUNT_REVERSE_KEY,body())
                .bean(mediaCardService,"allocateMediaCard");

        from("direct:reverseAccount")
                .transform(header(OPEN_ACCOUNT_REVERSE_KEY))
                .log("补偿开户信息:${body}")
                .bean(accountInfoService,"reverseAccount");

        from(RouteInfo.CHECK_PROD_INFO.servNo)
                .routeDescription(RouteInfo.CHECK_PROD_INFO.desc)
                .routeId(RouteInfo.CHECK_PROD_INFO.id)
                .bean(prodSaleFacade, "checkProd");

        //from("direct:invoker").loadBalance().to()

    }

}